package com.example.springdemo.controller;

import com.example.springdemo.entity.User;
import com.example.springdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.list(); // 查询所有用户
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id); // 根据 ID 查询
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        boolean saved = userService.save(user); // 插入用户
        if (saved) {
            return user; // 返回保存后的用户（包含自动生成的 ID）
        } else {
            throw new RuntimeException("Failed to save user");
        }
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id); // 设置 ID
        boolean updated = userService.updateById(user); // 根据 ID 更新
        if (updated) {
            return userService.getById(id); // 返回更新后的用户
        } else {
            throw new RuntimeException("Failed to update user");
        }
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        boolean removed = userService.removeById(id); // 根据 ID 删除
        if (removed) {
            return "User deleted successfully";
        } else {
            throw new RuntimeException("Failed to delete user");
        }
    }
}
